<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Admin extends CI_Controller {

    private $tb_danhmuctt = 'danhmuctt';
    private $tb_danhmucsp = 'danhmucsp';
    private $tb_sanpham_manufacturer = 'sanpham_manufacturer';
    private $tb_lienhe = 'lienhe';
    private $tb_tintuc = 'tintuc';
    private $tb_sanpham = 'sanpham';
    private $tb_quangcao = 'quangcao';
    private $tb_setting = 'setting';
    private $tb_slideshow = 'slideshow';
    private $tb_users = 'users';
    //phan trang
    private $base_url_trang = '#';
    private $total_rows = 100;
    private $per_page = 10; // bang voi limit
    private $limit = 10; //bang voi perpage
    ///
    private $sochu = 20; //chon so chua cat dua vao intro bai viet
    private $id = '';

    /**
     * 
     * thay doi field trong file view cho dung voi bang hien = publish 
     */
    function __construct() {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper(array('form', 'text', 'chuyendoitv_helper', 'url'));
        //$this->lang->load('tank_auth'); 
        $this->load->model('Admin_model');
        $this->load->library(array('pagination', 'form_validation', 'security'));
        if ($this->auth()) {
            
        } else
            redirect('dangnhap');
    }

    function auth() {
        if ($this->session->userdata('logedin')) {
            if ($this->session->userdata('id') != '') {
                $this->session->set_userdata('upanh', 1); //nho bo khi hoan thanh
                return true;
            }
        } else {
            $this->session->set_userdata('auth', 'Bạn không có quyền truy cập');
            return false;
        }
    }

    public function index() {
        redirect('admin/xuly/setting/list');
    }

    function ajax() {
        if (!empty($_POST)) {
            $data = $this->security->xss_clean($_POST['data']);
        }
        $table = $this->security->xss_clean($this->uri->segment(3, 0)); //bang
        $field = $this->security->xss_clean($this->uri->segment(4, 0)); //truong cua bang
        $uri5 = $this->security->xss_clean($this->uri->segment(5, 0)); //id cua bai viet can thay doi
        $uri6 = $this->security->xss_clean($this->uri->segment(6, 0)); //id cua div can change
        $data = array(
            $field => $data
        );

        $this->db->where('id', $uri5);
        $this->db->update($table, $data);
        echo '#' . $uri6; // echo gui id ve 
    }

    function ajax_field() {
        if (!empty($_POST)) {
            $data = $this->security->xss_clean($_POST['data']);
        }
        $uri3 = $this->uri->segment(3, 0);
        $uri4 = $this->uri->segment(4, 0); //bang
        if (!empty($data)) {
            switch ($uri3) {
                case 'order':
                    $this->session->set_userdata('order', $data);
                    if ($this->session->userdata('sapxep')) {
                        if ($this->session->userdata('sapxep') == 'ASC') {
                            $this->session->set_userdata('sapxep', 'DESC');
                        } else
                            $this->session->set_userdata('sapxep', 'ASC');
                    } else
                        $this->session->set_userdata('sapxep', 'ASC');
                    break;
                case 'num':
                    $this->session->set_userdata('limit', $data);
                    break;
                case $uri3 == 'pub':
                    $data = $this->security->xss_clean($_POST);
                    $id = $data['id'];
                    $pulish = $data['publish'];
                    $tba = $this->uri->segment(4, 0);
                    $this->db->where('id', $id);
                    $this->db->update($tba, array('publish' => $pulish));
                    break;
                case $uri3 == 'like':
                    if (($uri4 == 'tintuc') || ($uri4 == 'danhmuctt')) {
                        $this->session->set_userdata('like', $data);
                    }
                    break;
                case 'where':
                    if ($uri4 = 'tintuc') {
                        switch ($data) {
                            case 'all':
                                $this->session->set_userdata('all_tintuc', 1);
                                $this->session->unset_userdata('value_where');
                                $this->session->unset_userdata('where');
                                break;
                            default:
                                $this->session->set_userdata('where', 'iddanhmuc');
                                $this->session->set_userdata('value_where', $data);
                                $this->session->set_userdata('all_tintuc', 0);
                                break;
                        }
                    }
                    if ($uri4 = 'sanpham') {
                        switch ($data) {
                            case 'all':
                                $this->session->set_userdata('all_sanpham', 1);
                                $this->session->unset_userdata('value_where');
                                $this->session->unset_userdata('where');
                                break;
                            default:
                                $this->session->set_userdata('where', 'category');
                                $this->session->set_userdata('value_where', $data);
                                $this->session->set_userdata('all_sanpham', 0);
                                break;
                        }
                    }
                    break;
            }
        }
    }

    function xuly() {
        //$this->session->set_userdata('order',0);
        $this->rounte = $this->security->xss_clean($this->uri->segment(3, 0)); //su chu run
        $dk = $this->security->xss_clean($this->uri->segment(4, 0)); //sau chu run
        $id = $this->security->xss_clean($this->uri->segment(5, 0)); //lay id
        $this->id = $id;
        if (!empty($_POST)) {
            if ($this->validate()) {
                $post_data = $_POST;
            } else {
                $dk = 'edit';
            }
        }
        if (empty($post_data)) {
            $post_data = '';
        }
        $data['page'] = $this->run($dk, $id, $post_data);
        $data['setting'] = $this->Admin_model->get_one($this->tb_setting);
        $data['contact_new'] = $this->Admin_model->get_number($this->tb_lienhe, array('trangthai' => 0));
        if (empty($data['contact_new'])) {
            $data['contact_old'] = $this->Admin_model->get_number($this->tb_lienhe, array('trangthai' => 1));
        }
        $this->load->view('admin/index', $data);
    }

    function run($dk, $id, $post_data = '') {
        if (!is_numeric($id)) {
            $id = 0;
        }
        if (!empty($this->rounte)) {
            $table = $this->rounte;
            $page = $this->rounte;
        } else
            $table = ''; //chua kiem tra co bang hay chua

        if (!empty($dk)) {
            switch ($dk) {
                case 'list':
                    if (!empty($post_data)) {
                        $data = $post_data;
                        $data = $this->xuly_dulieu($data, $table, $id);
                        if ($id) {
                            if (!empty($data['alias'])) {
                                $alias = $data['alias'];
                                $table;
                                $valueAlias = $this->Admin_model->get_one('alias', array('a_id' => $id, 'type' => $table));
                                if (!empty($valueAlias)) {
                                    $this->db->where(array('a_id' => $id, 'type' => $table));
                                    $this->db->update('alias', array('alias' => $alias));
                                } else {
                                    $this->db->insert('alias', array('a_id' => $id, 'type' => $table, 'alias' => $alias));
                                }
                            }
                            unset($data['alias']);
                            $this->db->where('id', $id);
                            $this->db->update($table, $data);
                            $this->session->set_userdata('thongbao', 'Đã Sửa xong');
                        } else {
                            if (isset($data['alias'])) {
                                $alias = $data['alias'];
                                unset($data['alias']);
                                $this->db->insert($table, $data);
                                $idLast = $this->db->insert_id();
                                if (!empty($alias)) {
                                    $alias = $alias;
                                    $type = $table;
                                    $this->db->insert('alias', array('a_id' => $idLast, 'type' => $type, 'alias' => $alias));
                                }
                            }else{
                               $this->db->insert($table, $data);
                            }
                            $this->session->set_userdata('thongbao', 'Đã thêm');
                        }
                        redirect(base_url() . 'admin/xuly/' . $page . '/list');
                    }
                    //hien thi danh sach
                    $this->base_url_trang = base_url() . 'admin/xuly/' . $page . '/list/';
                    if ($table != $this->session->userdata('sec_table')) {
                        //check xem co trung bang hay khong de kiem tra xem dang o trang cu hoac trang moi xoa session//bang ba
                        // bang bang session bang thi kiem tra order_by
                        $this->session->set_userdata('order', 0);
                        $this->session->set_userdata('sec_table', $table);
                        $this->session->set_userdata('where', 0);
                    }
                    if ($this->session->userdata('order')) {
                        $order = array('truong' => $this->session->userdata('order'), 'sapxep' => $this->session->userdata('sapxep'));
                    } else
                        $order = array();

                    // limit start dung sau 
                    if (!$this->session->userdata('limit')) {
                        $this->session->set_userdata('limit', $this->limit);
                    } else
                        $this->limit = $this->session->userdata('limit');
                    $this->per_page = $this->limit; // so record tren 1 trang bang limit
                    if ($id) {
                        $start_limit = $id;
                    } else
                        $start_limit = 0;
                    if ($this->session->userdata('change_cat')) {
                        $start_limit = 0;
                        $this->session->set_userdata('change_cat', 0);
                    }
                    $limit = $this->limit;

                    //where
                    if ($this->session->userdata('where')) {
                        $where = $this->session->userdata('where');
                        $value = $this->session->userdata('value_where');
                        $where = array($where => $value);
                    } else
                        $where = array();
                    //like
                    if ($this->session->userdata('like')) {
                        $like = $this->session->userdata('like');
                    } else {
                        $like = array();
                    }

                    $this->total_rows = $this->Admin_model->get_number($table, $where);
                    $this->phantrang();
                    //thong baohien so ket qua tren tong so record
                    $tt_limit = $this->limit + $id;
                    if ($this->limit >= $this->total_rows) {
                        $total = $this->total_rows;
                    } else
                        $total = $tt_limit;
                    $result_mensenger = "danh sách từ $id - $total  của $this->total_rows";

                    $cat = $this->cat($table);
                    $data = array('data' => $this->Admin_model->get_data($table, $where, $order, $limit, $start_limit, '', $like), 'result_mensenger' => $result_mensenger, 'cat' => $cat);
                    return $this->load->view('admin/content/' . $page . '_list', $data, true); //true la k hien chi tra ve
                    break;
                case 'edit':
                    $cat = $this->cat($table);
                    //hien thi sua
                    if ($id) {
                        $valueAlias = $this->Admin_model->get_one('alias', array('a_id' => $id, 'type' => $table));
                        $data = array('data' => $this->Admin_model->get_one($table, array('id' => $id)), 'cat' => $cat, 'alias' => $valueAlias);
                    } else {
                        $valueAlias = $this->Admin_model->get_one('alias', array('a_id' => $id, 'type' => $table));
                        $data = array('cat' => $cat, 'alias' => $valueAlias);
                    }
                    return $this->load->view('admin/content/' . $page . '_edit', $data, true); //true la k hien chi tra ve
                    break;
                case 'xoa':
                    if ($id) {
                        $this->db->delete($table, array('id' => $id));
                        $this->db->delete('alias', array('a_id' => $id, 'type' => $table));
                        $this->session->set_userdata('thongbao', 'Đã thực hiện');
                        redirect(base_url() . 'admin/xuly/' . $page . '/list');
                    }
                    break;
            }
        }
    }

    function xuly_dulieu($data, $table, $id = '') {
        if ($table == 'users') {
            if (!empty($data['new_password_key']) && trim($data['new_password_key']) != '') {
                $data['password'] = sha1(md5($data['new_password_key']));
            }
        }
        if (!empty($data['metades'])) {
            $data['metades'] = trim($data['metades']);
        }
        if (!empty($data['metakey'])) {
            $data['metakey'] = trim($data['metakey']);
        }

        // danh muc san pham noi bat
        // san pham noi bat ban chay tieu bieu
        //if($table=='sanpham'){
        // if(empty($data['time'])){
        //     $data['time']=time() + $data['time']*1000;
        // }
        // xu ly thuoc tinh san pham   
        //}
        // san pham
        if (($table == 'danhmuctt') || ($table == 'tintuc') || ($table == 'danhmucsp') || ($table == 'sanpham') || ($table == 'sanphamdg')) {
            if (empty($data['alias'])) {
                $them = 0;
                $data['alias'] = creat_alias($data['title']);
            } else {
                $data['alias'] = creat_alias($data['alias']);
            }
            $alias = $data['alias'];

            $dieukien = 1;
            while ($dieukien) {
                if (!empty($id)) {
                    $nd = array('alias' => $alias, 'a_id !=' => $id, 'type' => $table);
                } else
                    $nd = array('alias' => $alias);
                $check = $this->Admin_model->check_trung($nd, 'alias');
                if ($check) {
                    $dieukien = $dieukien + 1;
                    $alias = $alias . $dieukien;
                } else
                    $dieukien = 0;
            }
            $data['alias'] = $alias;


            //xu ly bai viet            
            if ($table == 'tintuc') {
                if (empty($data['image'])) {
                    $ddd = $data['fulltext'] . '<img src="upload/default.jpg"/>'; //'images/default.jpg'
                    $diachianh = laydiachianh($ddd); //lay dia chi anh
                    $data['image'] = $diachianh;
                }
                if (empty($data['introtext'])) {
                    //character_limiter($row_baiviet->title,35);
                    //xu ly introtext
                    $loaibohtml = loaibo_html($data['fulltext']); //loai bo ma html       
                    $loaibohtml = word_limiter($loaibohtml, $this->sochu); // lay 30 chu
                    $loaibohtml = trim($loaibohtml);
                    $data['introtext'] = $loaibohtml;
                    $data['fulltext'] = loaibo_div_html($data['fulltext']);
                    if (empty($data['metades'])) {
                        $data['metades'] = $loaibohtml;
                    }
                }
            }
            //en xu ly anh+ meta des bai viet
            //xu ly anh product           
            if ($table == 'sanpham' && !empty($data['img'])) {
                $image = $data['img'];
                $data['img'] = implode(',', $image);
            }
            //en xu ly anh product

            if (empty($data['metakey']) || empty($data['metades'])) {
                $setting = $this->Admin_model->get_one('setting', array('id' => 1));
                if (empty($data['metakey'])) {
                    $data['metakey'] = $setting->metakey;
                }
                if (empty($data['metades'])) {
                    $data['metades'] = $setting->metades;
                }
            }
        }
        //en danh muc voi tin tuc       
        return $data;
    }

    ///////////////////////////
    function capnhat_slsanpham($dieuhuong = '', $id_danhmuc) {// cap nhat so luong san pham cho dnah muc(hancode)
        switch ($dieuhuong) {
            case 'them':
                $dt = $this->Admin_model->get_data('danhmucsp');
                foreach ($dt as $dt1) {
                    $mdt[$dt1->id] = $dt1;
                }
                $this->child_cat($id_danhmuc, $mdt);
                break;
            case 'xoa':
                $dt = $this->Admin_model->get_data('danhmucsp');
                foreach ($dt as $dt1) {
                    $mdt[$dt1->id] = $dt1;
                }
                $this->child_cat_xoa($id_danhmuc, $mdt);
                break;
        }
    }

    function child_cat($id = 0, $mdt) {// lay danh muc con nho nhat 
        $data1 = $mdt[$id];
        $data1->total = $data1->total + 1;
        $this->db->where('id', $data1->id);
        $this->db->update('danhmucsp', $data1);
        if (!empty($data1->parentid)) {
            $this->child_cat($data1->parentid, $mdt);
        }
    }

    function child_cat_xoa($id = 0, $mdt) {// lay danh muc con nho nhat 
        $data1 = $mdt[$id];
        $data1->total = $data1->total - 1;
        $this->db->where('id', $data1->id);
        $this->db->update('danhmucsp', $data1);
        if (!empty($data1->parentid)) {
            $this->child_cat($data1->parentid, $mdt);
        }
    }

    ////////////////////////////   
    function cat($table) {
        if ($this->id) {
            $where = array('id !=' => $this->id);
        } else
            $where = '';
        switch ($table) {

            case 'danhmuctt':
                return $this->getid($this->Admin_model->get_data($table, $where));
                break;
            case 'tintuc':
                $danhmuctt = $this->getid($this->Admin_model->get_data('danhmuctt'));
                $danhmucsp = $this->getid1($this->Admin_model->get_data('danhmucsp'));
                return array('danhmucsp' => $danhmucsp, 'danhmuctt' => $danhmuctt);
                break;
            case 'danhmucsp':
                return $this->getid($this->Admin_model->get_data($table, $where));
                break;
            case 'sanpham':
                $category = $this->getid($this->Admin_model->get_data('danhmucsp'));
                return array('category' => $category);
                break;

            default:
                return true;
                break;
        }
    }

    function validate() {
        switch ($this->rounte) {
            case 'hotro':
                $this->form_validation->set_rules('name', 'Tên', 'required|xss_clean|min_length[4]|max_length[20]');
                $this->form_validation->set_rules('yahoo', 'Yahoo', 'required|xss_clean|min_length[4]|max_length[20]');
                $this->form_validation->set_rules('mobile', 'Điện thoại', 'required|xss_clean|numeric|min_length[9]|max_length[12]');
                break;
            case 'tintuc':
                $this->form_validation->set_rules('title', 'Tên danh mục', 'required|xss_clean|min_length[2]');
                $this->form_validation->set_rules('noibat', 'nổi bật', 'numeric');
                break;
            case 'sanpham':
                $this->form_validation->set_rules('title', 'Tên sản phẩm', 'required|xss_clean|min_length[2]');
                break;
            case 'danhmuctt':
                $this->form_validation->set_rules('title', 'Tên danh mục', 'required|xss_clean|min_length[2]');
                $this->form_validation->set_rules('publish', 'Hiển thị', 'required|numeric');
                break;
            default:
                return true;
        }
        if ($this->form_validation->run() == true) {
            return true;
        } else
            return false;
    }

    function phantrang() {
        $this->load->library('pagination');
        $config['base_url'] = $this->base_url_trang;
        $config['total_rows'] = $this->total_rows;
        $config['per_page'] = $this->per_page;
        $config['uri_segment'] = 5;
        $config['num_links'] = 10;
        $config['first_link'] = '<<';
        $config['first_tag_open'] = '<li class="firt_pag">'; //div cho chu <<
        $config['first_tag_close'] = '</li>'; //div cho chu <<
        $config['last_link'] = '>>';
        $config['last_tag_open'] = '<li class="last_pag">';
        $config['last_tag_close'] = '</li>';
        //-------next-
        $config['next_link'] = 'next &gt;';
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        //------------preview
        $config['prev_link'] = '&lt; prev';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
        // ------------------cu?npage
        $config['cur_tag_open'] = '<li class="current">';
        $config['cur_tag_close'] = '</li>';
        //--so 
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        //-----
        $this->pagination->initialize($config);
    }

    function logout() {
        $this->session->unset_userdata('id');
        $this->session->unset_userdata('logedin');
        redirect('dangnhap');
    }

    function add_rep($num) {
        $prep = '';
        for ($i = 1; $i <= $num - 1; $i++) {
            $prep.=' &nbsp;&nbsp;+';
        }
        return $prep;
    }

    function getid($dat) {
        $this->sele = '';
        if ($dat) {
            foreach ($dat as $v) {
                $data[$v->parentid][] = $v;
            }

            $this->menucreat($data, 0);
        }
        return $this->sele;
    }

    function menucreat($data, $id = 0, $leve = 0) {
        $leve++;
        foreach ($data[$id] as $dulieu) {
            $this->sele .='<option id= "' . $dulieu->id . '" value = "' . $dulieu->id . '">';

            if ($id == 0) {
                $this->sele .=$this->add_rep($leve) . $dulieu->title;
            } else {
                $this->sele .=$this->add_rep($leve) . $dulieu->title;
            }


            if (!empty($data[$dulieu->id])) {
                $this->menucreat($data, $dulieu->id, $leve);
            }
            $this->sele .='</option>';
        }$leve--;
    }

    function getid1($dat) {
        if ($dat) {
            foreach ($dat as $v) {
                $data[$v->parentid][] = $v;
            }

            $this->menucreat1($data, 0);
        }
        return $this->sele1;
    }

    function menucreat1($data, $id = 0, $leve = 0) {
        $leve++;
        foreach ($data[$id] as $dulieu) {
            $this->sele1 .='<option id= "' . $dulieu->id . '" value = "' . $dulieu->id . '">';

            if ($id == 0) {
                $this->sele1 .=$this->add_rep($leve) . $dulieu->title;
            } else {
                $this->sele1 .=$this->add_rep($leve) . $dulieu->title;
            }


            if (!empty($data[$dulieu->id])) {
                $this->menucreat1($data, $dulieu->id, $leve);
            }
            $this->sele1 .='</option>';
        }$leve--;
    }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */